package com.atguigu.servlet;

import javax.servlet.*;
import java.io.File;
import java.io.IOException;

/**
 * @ Author:任留辉
 * @ Description:
 * @ Date:Created in 10:04 2021/3/9 0009
 */
public class Servlet implements javax.servlet.Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
//ServletConfig的功能一：获取servlet的友好名称
        String servletName = servletConfig.getServletName();
        System.out.println("获取servlet的友好名称 = " + servletName);
        //ServletConfig的功能二：获取servlet的初始化参数
        String testInitParam = servletConfig.getInitParameter("testInitParam");
        System.out.println("获取servlet的初始化参数 = " + testInitParam);
        //ServletConfig的功能三：获取ServletContext对象
        ServletContext servletContext = servletConfig.getServletContext();
        System.out.println("获取ServletContext对象 = " + servletContext);
        //ServletContext的功能1：获取当前工程的初始化参数
        String testContextParam = servletContext.getInitParameter("testContextParam");
        System.out.println("获取当前工程的初始化参数 = " + testContextParam);
        //ServletContext的功能2：获取上下文路径
        String realPath = servletContext.getRealPath("");
        System.out.println("获取上下文路径 = " + realPath);


/**
 * ServletContext的功能3：获取当前工程的部署路径（输出路径或编译路径）
 * servletContext.getRealPath("")：获取当前工程的部署路径
 * D:\IDEA\workspace\SH0108\out\artifacts\day06_servlet_war_exploded
 * servletContext.getRealPath("test");获取当前工程的部署路径下某个目录的路径
 * D:\IDEA\workspace\SH0108\out\artifacts\day06_servlet_war_exploded\photo
 */
        //获取chain所对应的File文件对象
        String anger = servletContext.getRealPath("anger");
        File file = new File(anger);
        if (!file.exists()){
            file.mkdir();
        }
        //ServletContext的功能4：作为一个域对象，可以在整个工程的范围中共享数据
       servletContext.setAttribute("test", "未来没有黑暗，光明就在前方");
        Object test = servletContext.getAttribute("test");
        System.out.println("作为一个域对象 = " + test);

    }


    @Override
    public ServletConfig getServletConfig() {

        return null;
    }

    /**
     * service方法专门处理请求和响应
     *
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //转发
        servletRequest.getRequestDispatcher("/success.html").forward(servletRequest, servletResponse);

    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
